/*
 * @Author: 张通
 * @Date: 2021-04-02 11:24:27
 * @LastEditors: william
 * @LastEditTime: 2025-05-29 10:25:40
 * @Description: file content
 */
import router from '@/router'
import NProgress from '@/utils/nprogress'
import { getUmsToken, setUmsToken } from '@/utils/cookies'

const userStore = useOutsideUserStore()
const permissionStore = usePermissionStore()
const whiteList = ['driverOrder'] // 无重定向白名单

permissionStore.generateRoutes(userStore.menus)

router.beforeEach(async (to, from, next) => {
  console.log('router.beforeEach', to, from)
  // 将地址栏上的token存储到cookies中
  const urlData = to.query
  urlData.token && setUmsToken(urlData.token)
  // 启动进度条
  NProgress.start()
  const hasToken = getUmsToken() // 判断是否登录
  // 未登录，判断是否在白名单中
  if (whiteList.includes(to.name)) {
    next()
  } else if (hasToken) {
    if (to.path === '/login') {
      // 已登录，访问登录页，跳转到首页
      next({ path: '/' })
    } else {
      if (!Object.keys(userStore.userInfo).length) {
        await userStore.getUserInfo()
        if (to.path === '/404' && to.redirectedFrom) {
          // 防止第一次没匹配上,可以重复匹配一次
          next({
            path: to.redirectedFrom.path,
            query: to.redirectedFrom.query
          })
          return
        }
      }
      to.path !== '/404'
      next()
    }
  } else {
    // 不在登录页，重定向到登录页
    to.path === '/login' ? next() : redirectToLogin(to, next)
  }
})

router.afterEach(() => {
  // 后置守卫，保证每次路由跳转结束时关闭进度条
  NProgress.done()
})

// 复写warn方法方便检查由于使用name跳转无法监控404的问题
window.console.warn = (...rest) => {
  const err = Array.from(rest)[0] + ''
  if (
    err &&
    err.includes('Route with name') &&
    err.includes('does not exist')
  ) {
    setTimeout(() => {
      router.replace('/404')
    })
  }
}

// 重定向到登录页
function redirectToLogin(to, next) {
  if (to.path === '/404' || to.path === '/403') {
    next(`/login`)
  } else {
    const params = new URLSearchParams(to.query)
    const queryString = params.toString()
    const redirect = queryString ? `${to.path}?${queryString}` : to.path
    next(`/login?redirect=${encodeURIComponent(redirect)}`)
  }
}
